
//
//  PayViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/7.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
import Networking

class PayViewController: BaseViewController, BottomShadow {

    @IBOutlet var statusButtons: [UIButton]!
    @IBOutlet weak var mainView: UIView!
    
    var orderId: String?
    var selectIndex :String = "1"
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
    }

    override func setNavigation() {
    }
    
    @IBAction func aliTap(_ sender: UIButton) {
        sender.isSelected = true
        for button in statusButtons {
            if button != sender {
                button.isSelected = false;
            }
        }
        selectIndex = "1"
    }
    
    @IBAction func weChatTap(_ sender: UIButton) {
        sender.isSelected = true
        for button in statusButtons {
            if button != sender {
                button.isSelected = false;
            }
        }
        selectIndex = "0"
    }
    
    override func returnVC() {
        CustomShowAlertView().show(title:
            """
            确定需要取消付款吗?
            订单会保留两个小时，请尽快支付
            """) { (isDone) in
            if isDone {
                let myOrderVC = NewOrderListViewController(nibName: "\(NewOrderListViewController.self)", bundle: nil)
                self.navigationController?.pushViewController(myOrderVC, animated: true)
            }
        }
    }
    
    
    @IBAction func doneTap(_ sender: UIButton) {
        let paramaters: [String: Any] = ["orderNumber":orderId!,"type":selectIndex]
        self.pay(paramaters: paramaters)
    }
    
    func pay(paramaters:[String: Any]) -> Void {
        let requesturl = "\(BaseURL)\(payUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let charge=json["data"]
                                        if self.selectIndex == "0" {
                                            let req=PayReq()
                                            req.timeStamp=charge["timestamp"].uInt32Value
                                            req.partnerId=charge["partnerid"].stringValue
                                            req.package=charge["package"].stringValue
                                            req.nonceStr=charge["noncestr"].stringValue
                                            req.sign=charge["sign"].stringValue
                                            req.prepayId=charge["prepayid"].stringValue
                                            WXApiManager.shared.payAlertController(self, request: req, paySuccess: {
                                                self.showToast(msg: "支付成功")
                                                let myOrderVC = NewOrderListViewController(nibName: "\(NewOrderListViewController.self)", bundle: nil)
                                                self.navigationController?.pushViewController(myOrderVC, animated: true)
                                            }, payFail: {
                                                self.showToast(msg: "支付失败")
                                                let myOrderVC = NewOrderListViewController(nibName: "\(NewOrderListViewController.self)", bundle: nil)
                                                self.navigationController?.pushViewController(myOrderVC, animated: true)
                                            })
                                        }else {
                                            let orderString=json["data"]["alipay"].stringValue
                                            AliPayManager.shared.payAlertController(self, request:orderString, paySuccess: {
                                                self.showToast(msg: "支付成功")
                                                let myOrderVC = NewOrderListViewController(nibName: "\(NewOrderListViewController.self)", bundle: nil)
                                                self.navigationController?.pushViewController(myOrderVC, animated: true)
                                            }, payFail: {
                                                self.showToast(msg: "支付失败")
                                                let myOrderVC = NewOrderListViewController(nibName: "\(NewOrderListViewController.self)", bundle: nil)
                                                self.navigationController?.pushViewController(myOrderVC, animated: true)
                                            })
                                        }
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"下单失败")
                                self.navigationController?.popViewController(animated: true)
                            }
                            
        }
    }
    
    func fetchOrderInfo(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(myOrderUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let myOrderVC = NewOrderListViewController(nibName: "\(NewOrderListViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(myOrderVC, animated: true)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
}
